package com.example.demo.service.impl;

import com.example.demo.entity.LabCategory;
import com.example.demo.repository.LabCategoryRepository;
import com.example.demo.service.LabCategoryService;
import lombok.RequiredArgsConstructor;
import org.springframework.http.HttpStatus;
import org.springframework.stereotype.Service;
import org.springframework.web.server.ResponseStatusException;

import java.util.List;
import java.util.Optional;

@Service
@RequiredArgsConstructor
public class LabCategoryServiceImpl implements LabCategoryService {

    private final LabCategoryRepository categoryRepository;

    @Override
    public LabCategory createCategory(LabCategory category) {
        if (categoryRepository.existsByName(category.getName())) {
            throw new ResponseStatusException(HttpStatus.BAD_REQUEST, "分类名称已存在");
        }
        return categoryRepository.save(category);
    }

    @Override
    public LabCategory updateCategory(LabCategory category) {
        if (!categoryRepository.existsById(category.getId())) {
            throw new ResponseStatusException(HttpStatus.NOT_FOUND, "分类不存在");
        }
        return categoryRepository.save(category);
    }

    @Override
    public void deleteCategory(Long id) {
        if (!categoryRepository.existsById(id)) {
            throw new ResponseStatusException(HttpStatus.NOT_FOUND, "分类不存在");
        }
        categoryRepository.deleteById(id);
    }

    @Override
    public Optional<LabCategory> getCategoryById(Long id) {
        return categoryRepository.findById(id);
    }

    @Override
    public Optional<LabCategory> getCategoryByName(String name) {
        return categoryRepository.findByName(name);
    }

    @Override
    public List<LabCategory> getAllCategories() {
        return categoryRepository.findAll();
    }
} 